// -----------------------------------------------------------------------
//  <copyright file="HashHelper.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2022 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2022-12-22 23:36</last-date>
// -----------------------------------------------------------------------

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;


namespace DaprPlus.Hash;

public static class HashHelper
{
    /// <summary>
    /// 创建自签名证书
    /// </summary>
    /// <param name="fileName">证书保存文件</param>
    /// <param name="password">证书安全密钥</param>
    /// <param name="distinguishedName">e.g: CN=Liuliu Encryption Certificate</param>
    /// <param name="keyUsages">证书使用目的</param>
    public static void CreateRsaCertificate(string fileName, string password, string distinguishedName, X509KeyUsageFlags keyUsages)
    {
        using var algorithm = RSA.Create(keySizeInBits: 2048);
        var subject = new X500DistinguishedName(distinguishedName);
        var request = new CertificateRequest(subject, algorithm, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        request.CertificateExtensions.Add(new X509KeyUsageExtension(keyUsages, critical: true));
        var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.Now.AddYears(2));
        File.WriteAllBytes(fileName, certificate.Export(X509ContentType.Pfx, password));
    }
}
